﻿using System.Collections.Generic;
using UnityEngine;
using Object = System.Object;

namespace LoginUI.UI
{
    public class UIManager
    {
        // UIManager 单例模式
        private static UIManager _instance;

        public static UIManager Instance
        {
            get
            {
                if (_instance == null) _instance = new UIManager();
                return _instance;
            }
        }

        // 构造函数
        private UIManager()
        {
            CanvasTrans = GameObject.Find("Canvas").transform;
            GameObject.DontDestroyOnLoad(CanvasTrans);
        }

        public Transform CanvasTrans
        {
            get;
            set;
        }

        // 面板字典
        private Dictionary<string, BasePanel> _panelDict = new();

        // 隐藏面板
        public void HidePanel<T>(bool isFade = true) where T : BasePanel
        {
            var panelName = typeof(T).Name;
            if (_panelDict.ContainsKey(panelName))
            {
                if (isFade)
                {
                    var panel = _panelDict[panelName];
                    panel.hideMe(() =>
                    {
                        GameObject.Destroy(_panelDict[panelName].gameObject);
                        _panelDict.Remove(panelName);
                    });
                } else
                {
                    GameObject.Destroy(_panelDict[panelName].gameObject);
                    _panelDict.Remove(panelName);
                }
            }
        }

        // 获取面板
        public T GetPanel<T>() where T : BasePanel
        {
            var panelName = typeof(T).Name;
            if (_panelDict.ContainsKey(panelName)) return _panelDict[panelName] as T;
            return null;
        }

        // gameObject 绑定了 basePanel; basePanel=> panel.gameObject 获取游戏物体;
        // 显示面板
        public T ShowPanel<T>() where T : BasePanel
        {
            // 1. 先根据T类型获取面板名称
            var panelName = typeof(T).Name;
            // 2. 使用面板名称在面板字典中查找面板,
            // 如果没有找到,
            //  则创建面板,添加到CanvasTrans中作为子对象,并添加到面板字典中
            // 如果找到了,则直接返回面板
            if (!_panelDict.ContainsKey(panelName))
            {
                var panelObj = GameObject.Instantiate(Resources.Load<GameObject>("UI/Prefabs/" + panelName));
                panelObj.transform.SetParent(CanvasTrans, false);
                var panel = panelObj.GetComponent<T>();
                _panelDict.Add(panelName, panel);
                panel.ShowMe();
                panel.Init();
                return panel;
            } else
            {
                var panel = _panelDict[panelName];
                panel.Init();
                return panel as T;
            }
        }
    }
}